const { execSql } = require("../utils/db")

class history {
    /**
     * 如果有id 就返回某一条数据
     * 如果没有id 就返回这个 用户的所有数据
     */
    static async get(uid, page = 1, id = null) {
        let where = ''
        if (id) {
            where = ` and H.gid=${id} `
        }
        let start = (page - 1) * 10
        // 获取每页数据
        let res = await execSql(`select G.*,H.* from lv_history as H,lv_goods as G where H.gid=G.id and H.uid=${uid} ${where} order by H.orders desc limit ${start},10`)
        let sums = await execSql(`select count(*) as num from lv_history where uid=${uid} ${where}`)
        let pageCount = 1;
        if (sums.length > 0) {
            pageCount = Math.ceil(sums[0].num / 10)
        }
        return { list: res, pageCount }
    }

    static async add(id, uid) {
        if (!id || !uid) {
            return false
        } else {
            // 先查询 看看用户以前有没有添加过这个商品的历史 
            let res = await execSql(`select * from lv_history where uid=${uid} and gid=${id}`)
            if (res.length > 0) {
                //如果用户已经添加了 历史  那么就 让排序字段++ 
                await execSql(`update lv_history set orders=orders+1 where uid=${uid} and gid=${id}`)
            } else {
                // 如果没有添加过历史 那么就将这个数据 添加进去
                await execSql(`INSERT INTO lv_history (uid, gid) VALUES ('${uid}', '${id}')`)
            }
            return true
        }
    }
}
module.exports = history